const Multipart = require('../../utils/Multipart.min.js')
Page({

    data: {
        min: 15,//最少字数
        max: 200, //最多字数 (根据自己需求改变) 
        currentWordNumber: 0,
        mincount: false,
        imglist: [],
        types: ['日常', '服饰', '学具', '其它'],
    },
    //字数限制  
    input_descriptio(e) {
        // 获取输入框的内容
        var value = e.detail.value.trim();
        // 获取输入框内容的长度
        var len = parseInt(value.length);
        //最少字数限制
        if (len == 0)
            this.setData({
                mincount: false,
                description_value: value
            })
        else if (len < this.data.min)
            this.setData({
                mincount: true,
                description_value: value
            })
        else if (len >= this.data.min)
            this.setData({
                mincount: false,
                description_value: value
            })

        this.setData({
            currentWordNumber: len //当前字数  
        });
        //最多字数限制
        if (len > this.data.max) return;
        // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    },
    input_title(e) {
        this.setData({
            title_value: e.detail.value.trim()
        })
    },
    makeNumber(e) {//限制金额
        let value = e.detail.value
        let _value = value.replace(/[^\d]/g, '')
        let price_value = this.data.price_value
        if (_value > 500)
            _value = price_value
        this.setData({
            price_value: _value
        })

    },
    /*实现图片放大预览的js代码*/
    preview(event) {
        let index = event.currentTarget.dataset.index
        wx.previewImage({
            current: this.data.imglist[index], // 当前显示图片的http链接
            urls: this.data.imglist // 需要预览的图片http链接列表
        })
    },
    /*实现将相册或者照相的图片显示出来*/
    img_w_show() {
        let _imglist = [...this.data.imglist]
        if (_imglist > 9) {
            wx.showModal({
                title: '提示',
                content: '最多上传九张图片',
                confirmColor: "rgb(255,80,0)",
            })
            return
        }
        var _this = this
        wx.chooseImage({
            count: 9, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var imglist = res.tempFilePaths
                imglist = imglist.concat(_imglist)
                if (imglist.length > 9) {
                    wx.showModal({
                        title: '提示',
                        content: '最多上传九张图片',
                        confirmColor: "rgb(255,80,0)",
                    })
                    return
                }
                _this.setData({
                    imglist: imglist
                })
            },
            fail: function (error) {
                console.error('调用本地相册文件时出错')
                console.warn(error)
            },
            complete: function () { }
        })
    },
    /*图片右上角删除按钮功能的实现*/
    deleteImage: function (e) {
        let index = e.target.dataset.index
        let imglist = [...this.data.imglist]
        imglist.splice(index, 1)
        this.setData({
            imglist: imglist
        })
    },

    formSubmit: function (e) {
        let { title_value, type_value, description_value, price_value } = e.detail.value
        if (!title_value) {
            wx.showModal({
                title: '提示',
                content: '标题不能为空',
                confirmColor: "rgb(255,80,0)",
            })
            return
        } if (!description_value) {
            wx.showModal({
                title: '提示',
                content: '内容不能为空',
                confirmColor: "rgb(255,80,0)",
            })
            return
        } if (description_value.length < 15) {
            wx.showModal({
                title: '提示',
                content: '内容字数不能少于15字',
                confirmColor: "rgb(255,80,0)",
            })
            return
        } if (!price_value) {
            wx.showModal({
                title: '提示',
                content: '金额不能为空',
                confirmColor: "rgb(255,80,0)",
            })
            return
        }
        if (this.data.imglist.length === 0) {
            wx.showModal({
                title: '提示',
                content: '请上传图片',
                confirmColor: "rgb(255,80,0)",
            })
            return
        }


        const _data = {
            'id': 0,
            'title': '',
            'description': '',
            'price': 0,
            'price0': 0,
            'type': 0,
            'upTime': '',
            'userId': 0
        }
        _data.description = description_value
        _data.userId = wx.getStorageSync("userId")
        _data.price = price_value
        _data.title = title_value
        _data.type = type_value
        var myDate = new Date();
        _data.upTime = myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + '-' + myDate.getDate()
            + " " + myDate.getHours() + ":" + myDate.getMinutes();
        _data.id = wx.getStorageSync("userId") + myDate.valueOf()
        console.log(_data)
        wx.showLoading({
            title: '加载中',
            mask: true
        })
        let files = [...this.data.imglist]
        files = files.map((item) => {
            return { name: 'imgs', filePath: item }
        })
        let fields = []
        let url = `https:/xxxxx/xxx/xxx/${JSON.stringify(_data)}/${this.data.imglist.length}`
        new Multipart({
            files,
            fields,
        }).submit(url).then(({ data }) => {
            wx.hideLoading()
            if (data.state === 1) {
                this.setData({
                    imglist: [],
                    title_value: '',
                    description_value: '', 
                    price_value: ''
                })
                wx.showToast({
                    title: '上传成功',
                    icon: 'success',
                    duration: 2000
                })
            } else {
                wx.showToast({
                    title: ' 上传失败',
                    icon: 'error',
                    duration: 2000,
                    mask: false,
                })
            }
        })
    },
})